<script setup lang="ts">
import HandsonTable from 'handsontable'
import { registerAllModules } from 'handsontable/registry'
import 'handsontable/styles/handsontable.css'
import 'handsontable/styles/ht-theme-main.css'
// import 'handsontable/styles/ht-theme-horizon.css'
import '@/style/handsontable-theme.css'
import { registerLanguageDictionary, zhCN } from 'handsontable/i18n'
import { HyperFormula } from 'hyperformula'

import useTheme from '../useTheme'
import { REPORT_FORM_ID, REPORT_ID } from '@/enum/modules/report'
import type { LoadDataResponse } from './type'
import { HEADER_CELL_CLASS, READONLY_CELL_CLASS, ROUND_NUMBER as _ROUND_NUMBER } from '../config'
import useLoadReportDetail from './useLoadReportDetail'
import { saveReportDataOfSummaryCompanyElectricityCost } from '@/api/modules/dataReport'
import useValidate from '../useValidate'

defineOptions({ name: 'SummaryCompanyElectricity2' })
const props = defineProps<{
  time: string
}>()

// 电量电费汇总表精度保留到6位
const ROUND_NUMBER = _ROUND_NUMBER + 2

registerLanguageDictionary(zhCN)

// register Handsontable's modules
registerAllModules()

// 成本表
// eslint-disable-next-line
const reportId = REPORT_ID.ELECTRICITY_BILL_SUMMARY
const formId = REPORT_FORM_ID.ELECTRICITY_BILL_SUMMARY_2
// 当前企业名称
// const tenantName = ref('')
// 远程数据
const loadDataResponse = shallowRef<LoadDataResponse>()
const { res, loadReportData } = useLoadReportDetail()

const HEADERS = [
  [
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    '电费税率：',
    null,
    null,
  ],
  [
    '',
    '产量、入流量（万吨）',
    null,
    null,
    null,
    '成本电量（万kwh）',
    null,
    null,
    '成本电费（万元）',
    null,
    null,
    '单位产品电费（元/吨）',
    null,
    null,
    null,
  ],
  [
    null,
    '计划',
    '本月',
    '上月止累计',
    '本月止累计',
    '本月',
    '上月止累计',
    '本月止累计',
    '本月',
    '上月止累计',
    '本月止累计',
    '计划',
    '本月',
    '上月止累计',
    '本月止累计',
  ],
]

const wrapper = ref<HTMLElement>()
const hot = ref<HandsonTable>()

const newMergeCells = shallowRef<HandsonTable.GridSettings['mergeCells']>(
  [
    // { row: 0, col: 12, rowspan: 1, colspan: 1 },
    { row: 1, col: 0, rowspan: 2, colspan: 1 },
    { row: 1, col: 1, rowspan: 1, colspan: 4 },
    { row: 1, col: 5, rowspan: 1, colspan: 3 },
    { row: 1, col: 8, rowspan: 1, colspan: 3 },
    { row: 1, col: 11, rowspan: 1, colspan: 4 },
  ],
)

const attrs = useAttrs()
const readonly = computed<boolean>(() => {
  return attrs.readonly as boolean
})

// 加载数据
async function loadData() {
  if (!props.time)
    return
  await loadReportData(props.time, unref(formId))
  const src = loadDataResponse.value = unref(res)

  const dataList = []
  // 全公司用电所在行
  dataList.push([
    '全公司用电',
    // 等待公式填充
    ...Array(14).fill(null),
  ])
  // 原煤生产所在行
  dataList.push([
    '一、原煤生产',
    // 等待公式填充
    ...Array(14).fill(null),
  ])
  // 循环插入煤矿数据
  const mkDataList = src?.cost?.mkDataList
  if (mkDataList) {
    // 前面有5行
    const initial = 5
    for (let i = 0; i < mkDataList.length; i++) {
      // 当前行号
      const row = initial + i + 1
      const v = mkDataList[i]
      const array = []
      array.push(
        v.name,
        v.clJh,
        v.cl,
        v.clLastMonthTotal,
        // 产量本月止累计 = 上月止累计 + 本月
        `=ROUND(C${row}+D${row},${ROUND_NUMBER})`,
        v.dl,
        v.dlLastMonthTotal,
        // 电量本月止累计 = 上月止累计 + 本月
        `=ROUND(F${row}+G${row},${ROUND_NUMBER})`,
        // 本月电费要除上税率(N1单元格)
        `=IFERROR(ROUND(${v.df}/N1,${ROUND_NUMBER}),"")`,
        v.dfLastMonthTotal,
        // 电费本月止累计 = 上月止累计 + 本月
        `=ROUND(I${row}+J${row},${ROUND_NUMBER})`,
        v.dwcpDfJh,
        // 单位产品本月 = 本月电费 / 本月产量
        `=IFERROR(ROUND(I${row}/C${row},${ROUND_NUMBER}),"")`,
        // 单位产品上月止累计 = 上月止累计 / 上月产量
        `=IFERROR(ROUND(J${row}/D${row},${ROUND_NUMBER}),"")`,
        // 单位产品本月止累计 = 成本电费本月累计 / 产量本月止累计
        `=IFERROR(ROUND(K${row}/E${row},${ROUND_NUMBER}),"")`,
      )
      dataList.push(array)
    }
  }
  // 洗煤生产所在行
  dataList.push([
    '二、洗煤生产',
    // 等待公式填充
    ...Array(14).fill(null),
  ])
  // 循环插入洗煤厂数据
  const xmcDataList = src?.cost?.xmcDataList
  if (xmcDataList) {
    const initial = 5 + (mkDataList?.length ?? 0) + 1
    for (let i = 0; i < xmcDataList.length; i++) {
      // 当前行号
      const row = initial + i + 1
      const v = xmcDataList[i]
      const array = []
      array.push(
        array.push(
          v.name,
          v.clJh,
          v.cl,
          v.clLastMonthTotal,
        // 产量本月止累计 = 上月止累计 + 本月
        `=ROUND(C${row}+D${row},${ROUND_NUMBER})`,
        v.dl,
        v.dlLastMonthTotal,
        // 电量本月止累计 = 上月止累计 + 本月
        `=ROUND(F${row}+G${row},${ROUND_NUMBER})`,
        // 本月电费要除上税率(N1单元格)
        `=IFERROR(ROUND(${v.df}/N1,${ROUND_NUMBER}),"")`,
        v.dfLastMonthTotal,
        // 电费本月止累计 = 上月止累计 + 本月
        `=ROUND(I${row}+J${row},${ROUND_NUMBER})`,
        v.dwcpDfJh,
        // 单位产品本月 = 本月电费 / 本月产量
        `=IFERROR(ROUND(I${row}/C${row},${ROUND_NUMBER}),"")`,
        // 单位产品上月止累计 = 上月止累计 / 上月产量
        `=IFERROR(ROUND(J${row}/D${row},${ROUND_NUMBER}),"")`,
        // 单位产品本月止累计 = 成本电费本月累计 / 产量本月止累计
        `=IFERROR(ROUND(K${row}/E${row},${ROUND_NUMBER}),"")`,
        ),
      )
      dataList.push(array)
    }
  }

  const data = [
    ...HEADERS,
    ...dataList,
  ]
  // 填充公式
  if (data.length > HEADERS.length) {
    // 赋值到税率单元格（N1)
    const electricityTariff = mkDataList?.[0]?.electricityTariff
      || xmcDataList?.[0]?.electricityTariff || null
    // N1 赋值
    data[0][13] = electricityTariff
    const formulas = generateFormulas()
    for (const key in formulas) {
      const item = formulas[key as keyof typeof formulas]
      if (item.length) {
        for (const { row, col, exp } of item) {
          data[+row][+col] = exp
        }
      }
    }
  }
  hot.value?.loadData(data)
}

// 生成公式
function generateFormulas() {
  const result = {
    // 原煤生产所在行公式（行索引为4）
    mkFormulas: [] as { row: number | string, col: number | string, exp: string }[],
    // 洗煤生产所在行公式（行索引为4 + 原煤生产行数 + 1）
    xmcFormulas: [] as { row: number | string, col: number | string, exp: string }[],
    // 全公司用电所在行公式（行索引为3）
    allFormulas: [] as { row: number | string, col: number | string, exp: string }[],
  }
  const src = loadDataResponse.value
  const mkDataList = src?.cost?.mkDataList
  const xmcDataList = src?.cost?.xmcDataList
  if (mkDataList) {
    // 更新原煤生产所在行公式（行索引为4）
    const r1 = 4
    const r2 = r1 + mkDataList.length + 1
    result.mkFormulas.push(...[
      [r1, '1', `=ROUND(SUM(B${r1 + 2}:B${r2}),${ROUND_NUMBER})`],
      [r1, '2', `=ROUND(SUM(C${r1 + 2}:C${r2}),${ROUND_NUMBER})`],
      [r1, '3', `=ROUND(SUM(D${r1 + 2}:D${r2}),${ROUND_NUMBER})`],
      // 产量本月止累计
      [r1, '4', `=ROUND(C${r1 + 1}+D${r1 + 1},${ROUND_NUMBER})`],
      [r1, '5', `=ROUND(SUM(F${r1 + 2}:F${r2}),${ROUND_NUMBER})`],
      [r1, '6', `=ROUND(SUM(G${r1 + 2}:G${r2}),${ROUND_NUMBER})`],
      // 电量本月止累计
      [r1, '7', `=ROUND(F${r1 + 1}+G${r1 + 1},${ROUND_NUMBER})`],
      [r1, '8', `=ROUND(SUM(I${r1 + 2}:I${r2}),${ROUND_NUMBER})`],
      [r1, '9', `=ROUND(SUM(J${r1 + 2}:J${r2}),${ROUND_NUMBER})`],
      // 电费本月止累计
      [r1, '10', `=ROUND(I${r1 + 1}+J${r1 + 1},${ROUND_NUMBER})`],
      [r1, '11', `=ROUND(SUM(L${r1 + 2}:L${r2}),${ROUND_NUMBER})`],
      // 单价-本月
      [r1, '12', `=IFERROR(ROUND(I${r1 + 1}/C${r1 + 1},${ROUND_NUMBER}),"")`],
      // 单价-上月止累计
      [r1, '13', `=IFERROR(ROUND(J${r1 + 1}/D${r1 + 1},${ROUND_NUMBER}),"")`],
      // 单价-本月止累计
      [r1, '14', `=IFERROR(ROUND(K${r1 + 1}/E${r1 + 1},${ROUND_NUMBER}),"")`],
    ].map(([row, col, exp]) => ({ row, col, exp } as { row: number, col: string, exp: string })))
    // 更新洗煤生产所在行公式（行索引为5 + mkDataList.length）
    // 最后一行行号
    // 预计总行数 = 表头3行 + 全公司1行 + 原煤生产所在行1行 + 原煤数据行数 + 洗煤生产所在行1行 + 洗煤数据行数
    const e = 3 + 1 + (mkDataList?.length ?? 0) + 1 + (xmcDataList?.length ?? 0) + 1
    result.xmcFormulas.push(...[
      [r2, '1', `=ROUND(SUM(B${r2 + 2}:B${e}),${ROUND_NUMBER})`],
      [r2, '2', `=ROUND(SUM(C${r2 + 2}:C${e}),${ROUND_NUMBER})`],
      [r2, '3', `=ROUND(SUM(D${r2 + 2}:D${e}),${ROUND_NUMBER})`],
      // 产量本月止累计
      [r2, '4', `=ROUND(C${r2 + 1}+D${r2 + 1},${ROUND_NUMBER})`],
      [r2, '5', `=ROUND(SUM(F${r2 + 2}:F${e}),${ROUND_NUMBER})`],
      [r2, '6', `=ROUND(SUM(G${r2 + 2}:G${e}),${ROUND_NUMBER})`],
      // 电量本月止累计
      [r2, '7', `=ROUND(F${r2 + 1}+G${r2 + 1},${ROUND_NUMBER})`],
      [r2, '8', `=ROUND(SUM(I${r2 + 2}:I${e}),${ROUND_NUMBER})`],
      [r2, '9', `=ROUND(SUM(J${r2 + 2}:J${e}),${ROUND_NUMBER})`],
      // 电费本月止累计
      [r2, '10', `=ROUND(I${r2 + 1}+J${r2 + 1},${ROUND_NUMBER})`],
      [r2, '11', `=ROUND(SUM(L${r2 + 2}:L${e}),${ROUND_NUMBER})`],
      // 单价-本月
      [r2, '12', `=IFERROR(ROUND(I${r2 + 1}/C${r2 + 1},${ROUND_NUMBER}),"")`],
      // 单价-上月止累计
      [r2, '13', `=IFERROR(ROUND(J${r2 + 1}/D${r2 + 1},${ROUND_NUMBER}),"")`],
      // 单价-本月止累计
      [r2, '14', `=IFERROR(ROUND(K${r2 + 1}/E${r2 + 1},${ROUND_NUMBER}),"")`],
    ].map(([row, col, exp]) => ({ row, col, exp } as { row: number, col: string, exp: string })))
    // 更新全公司用电所在行公式（行索引为3）
    result.allFormulas.push(...[
      // 全公司产量、入流量不参与累加
      // [3, '1', `=ROUND(B${r1 + 1}+B${r2 + 1},${ROUND_NUMBER})`],
      // [3, '2', `=ROUND(C${r1 + 1}+C${r2 + 1},${ROUND_NUMBER})`],
      // [3, '3', `=ROUND(D${r1 + 1}+D${r2 + 1},${ROUND_NUMBER})`],
      // [3, '4', `=ROUND(C4+D4,${ROUND_NUMBER})`],
      [3, '1', null],
      [3, '2', null],
      [3, '3', null],
      // 产量本月止累计
      [3, '4', null],
      [3, '5', `=ROUND(F${r1 + 1}+F${r2 + 1},${ROUND_NUMBER})`],
      [3, '6', `=ROUND(G${r1 + 1}+G${r2 + 1},${ROUND_NUMBER})`],
      // 电量本月止累计
      [3, '7', `=ROUND(F4+G4,${ROUND_NUMBER})`],
      [3, '8', `=ROUND(I${r1 + 1}+I${r2 + 1},${ROUND_NUMBER})`],
      [3, '9', `=ROUND(J${r1 + 1}+J${r2 + 1},${ROUND_NUMBER})`],
      // 电费本月止累计
      [3, '10', `=ROUND(I4+J4,${ROUND_NUMBER})`],
      [3, '11', `=ROUND(L${r1 + 1}+L${r2 + 1},${ROUND_NUMBER})`],
      // 单价-本月
      [3, '12', `=IFERROR(ROUND(I4/C4,${ROUND_NUMBER}),"")`],
      // 单价-上月止累计
      [3, '13', `=IFERROR(ROUND(J4/D4,${ROUND_NUMBER}),"")`],
      // 单价-本月止累计
      [3, '14', `=IFERROR(ROUND(K4/E4,${ROUND_NUMBER}),"")`],
    ].map(([row, col, exp]) => ({ row, col, exp } as { row: number, col: string, exp: string })))
  }
  return result
}

// 更新单元格配置
function updateSettings() {
  if (hot.value) {
    const src = loadDataResponse.value
    const mkDataList = src?.cost?.mkDataList ?? []
    hot.value.updateSettings({
      mergeCells: newMergeCells.value,
      cell: [
        // 电费税率支持输入
        { row: 0, col: 13, readOnly: unref(readonly) || false, className: 'htLeft' },
      ],
      // B,C,L列（对应索引1，2，11）中数据所在行是可输入的
      cells: (row, col) => {
        if (row < HEADERS.length) {
          return (col === 0 || ((row === 0 && col === 1)))
            ? { className: `htLeft htMiddle ${HEADER_CELL_CLASS}` }
            : { className: `htCenter htMiddle ${HEADER_CELL_CLASS}` }
        }
        // A列居左对齐
        if (col === 0) {
          return { className: `htLeft htMiddle ${HEADER_CELL_CLASS}` }
        }
        if ([1, 2, 11].includes(col)) {
          // 从行号6开始
          // 洗煤生产所在行 5 + mkDataList.length
          if (row >= 5 && row !== mkDataList.length + 5) {
            return {
              readOnly: unref(readonly) || false,
              type: 'numeric',
              numericFormat: {
                pattern: '0.00',
              },
            }
          }
        }
        return {}
      },
    })
  }
}

function init() {
  if (!wrapper.value)
    return
  hot.value = new HandsonTable(wrapper.value, {
    fixedRowsTop: HEADERS.length,
    fixedColumnsStart: 1,
    selectionMode: 'single',
    readOnly: true,
    // disableVisualSelection: true,
    language: zhCN.languageCode,
    formulas: {
      engine: HyperFormula,
    },
    className: 'htCenter htMiddle',
    readOnlyCellClassName: READONLY_CELL_CLASS,
    stretchH: 'all',
    // autoColumnSize: true,
    colWidths: 160,
    manualColumnResize: true,
    colHeaders: true,
    rowHeaders: true,
    mergeCells: [],
    licenseKey: 'non-commercial-and-evaluation',
  })

  // 选中单元格后可以直接输入
  hot.value.addHook('afterSelectionEnd', (row, col) => {
    if (row < 0 || col < 0)
      return
    const value = hot.value?.getSourceDataAtCell(row, col)
    hot.value?.getActiveEditor()?.beginEditing()
    hot.value?.getActiveEditor()?.setValue(value)
  })

  // debug
  if (import.meta.env.VITE_REPORT_DEBUG === '1') {
    hot.value.addHook('afterSelection', (row, col) => {
      if (row > -1 && col > -1) {
        console.info(`[${row},${col}] ${hot.value?.getSourceDataAtCell(row, col)}`)
        document.execCommand('copy')
      }
    })
  }
}

async function bootstrap() {
  // 初始化实例
  init()
  // 加载数据和配置
  await loadData()
  updateSettings()
  generateHash()
}

onMounted(bootstrap)

const { isDark } = useTheme(async () => {
  // 主题切换后，重新初始化实例
  if (hot.value) {
    hot.value.destroy()
    hot.value = undefined
    await bootstrap()
  }
})

// 为了保存时从外部取数据使用
function getData() {
  const data = hot.value?.getSourceData() ?? []
  // 税率在行号索引为0
  const electricityTariff = (data[0] as any)[13]
  const src = loadDataResponse.value
  const ms = src?.cost?.mkDataList ?? []
  const m = ms.length ?? 0
  const ns = src?.cost?.xmcDataList ?? []
  const n = ns.length ?? 0
  if (m || n) {
    // 原煤生产所在行号为5
    const r1 = 5
    // 洗煤生产所在行号为5 + m + 1
    const r2 = r1 + m + 1
    // 原煤数据
    const d1 = data.slice(r1, r1 + m)
    // 洗煤数据
    const d2 = data.slice(r2, r2 + n)
    const dd1 = d1.map((v: any, i) => {
      return {
        socialCreditCode: ms[i].socialCreditCode,
        mkClJh: +v[1],
        xmcClJh: null,
        mkCl: +v[2],
        xmcCl: null,
        mkDfJh: +v[11],
        xmcDfJh: null,
      }
    })
    const dd2 = d2.map((v: any, i) => {
      return {
        socialCreditCode: ns[i].socialCreditCode,
        xmcClJh: +v[1],
        mkClJh: null,
        xmcCl: +v[2],
        mkCl: null,
        xmcDfJh: +v[11],
        mkDfJh: null,
      }
    })
    return {
      time: props.time,
      electricityTariff,
      dataList: [...dd1, ...dd2],
    }
  }
  return {
    time: props.time,
    electricityTariff,
    dataList: [],
  }
}

function validate() {
  return new Promise<boolean>((resolve, reject) => {
    if (hot.value) {
      const validator = useValidate(hot.value)
      validator().then(() => {
        resolve(true)
      }).catch(() => {
        reject(false)
      })
    }
    else {
      reject(false)
    }
  })
}

function submitForTab() {
  return new Promise((resolve, reject) => {
    saveReportDataOfSummaryCompanyElectricityCost(getData())
      .then(() => {
        resolve(true)
      })
      .catch((e) => {
        reject(e)
      })
  })
}

const hash = ref<number>(0)
function generateHash() {
  const s = getData()
  hash.value = simpleHash(JSON.stringify(s))
}

function checkHash() {
  return hash.value !== simpleHash(JSON.stringify(getData()))
}

defineExpose({
  getData,
  submitForTab,
  checkHash,
  generateHash,
  validate,
})
</script>

<template>
  <div class="h-full w-full">
    <div
      ref="wrapper" class="h-full w-full overflow-auto" :class="{
        'ht-theme-main-dark': isDark,
        'ht-theme-main': !isDark,
      }"
    />
  </div>
</template>
